package org.agile4j.patterns.adapter.logversion01;


import org.agile4j.patterns.adapter.LogModel;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

/**
 * 实现对日志文件的操作
 * 
 * @author user
 *
 */
public class LogFileOperateImpl implements ILogFileOperate {

	private String logFilePathName = "AdapterLog.log";

	/**
	 * 构造方法，传入文件的路径名称
	 * 
	 * @param logFilePathName
	 */
	public LogFileOperateImpl(String logFilePathName) {
		if (logFilePathName != null && logFilePathName.trim().length() > 0) {
			this.logFilePathName = logFilePathName;
		}
	}

	@Override
	public List<String> readLogFile() {
		List<String> all = new ArrayList<String>();
		Scanner scan = null;
		try {
			scan = new Scanner(new FileInputStream(new File(logFilePathName)));
			scan.useDelimiter("\n");
			while (scan.hasNext()) {
				all.add(scan.next());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			scan.close();
		}
		return all;
	}

	@Override
	public void writeLogFile(List<LogModel> list) {
		PrintStream util = null;
		try {
			util = new PrintStream(new FileOutputStream(new File(logFilePathName), true));
			Iterator<LogModel> ite = list.iterator();
			while (ite.hasNext()) {
				util.println(ite.next());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			util.close();
		}
	}

}
